/*
 * @(#)ErrorSqlDaoImpl.java   1.0  2021年11月12日
 * 
 * Copyright (c)	2014-2020. All Rights Reserved.	GuangZhou hhmk Technology Company LTD.
 */
package com.swift.dts.dao.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.swift.dts.dao.ErrorSqlTableDao;
import com.swift.dts.dao.model.ErrorSqlTable;
import com.swift.dts.dao.model.ErrorSqlTableKey;
import com.swift.dts.db.LocalDbDataSource;
import com.swift.dts.model.DtsBinlogMessage;
import com.swift.dts.model.SqlObject;
import com.swift.dts.util.CreateExecSql;
import com.swift.util.date.DateUtil;
import com.swift.util.type.JsonUtil;
import com.swift.util.type.TypeUtil;

/**
 * 添加说明
 * 
 * @author zhengjiajin
 * @version 1.0 2021年11月12日
 */
@Component
public class ErrorSqlDaoTableImpl implements ErrorSqlTableDao {

    @Autowired
    private LocalDbDataSource localDbDataSource;

    /**
     * @see com.swift.dts.dao.ErrorSqlDao#writeErrorSql(java.lang.String[])
     */
    @Override
    public void writeErrorSql(String destination, DtsBinlogMessage message, SqlObject sqlObject,String errorRem) {
        ErrorSqlTable errorSqlTable = new ErrorSqlTable();
        errorSqlTable.setCreateTime(DateUtil.formatDate(new Date()));
        errorSqlTable.setDestination(destination);
        errorSqlTable.setDataSource(message.getDestination());
        errorSqlTable.setDbName(message.getDatabase());
        errorSqlTable.setPkKey(sqlObject.getPk());
        errorSqlTable.setSqlStr(sqlObject.getSql());
        errorSqlTable.setTableName(message.getTable());
        errorSqlTable.setErrorRem(errorRem);
        save(errorSqlTable);
    }

    /**
     * @see com.swift.dts.dao.ErrorSqlTableDao#save(com.swift.dts.dao.model.ErrorSqlTable)
     */
    @Override
    public void save(ErrorSqlTable errorSqlTable) {
        String errorRem = errorSqlTable.getErrorRem();
        if(errorRem==null) errorRem="";
        String sql = "INSERT INTO " + ErrorSqlTable.TABLE_NAME
            + "(destination,data_source,db_name,table_name,pk_key,sql_str,error_rem,create_time)" + " VALUES("
            + "'"+ errorSqlTable.getDestination() + "',"
            + "'" + errorSqlTable.getDataSource() + "',"
            + "'" + errorSqlTable.getDbName() + "',"
            + "'" + errorSqlTable.getTableName() + "',"
            + "'" + errorSqlTable.getPkKey() + "',"
            + "'"+ CreateExecSql.formatValue(errorSqlTable.getSqlStr())  + "',"
            + "'"+ CreateExecSql.formatValue(errorRem) + "',"
            + "'" + errorSqlTable.getCreateTime() + "'"
            + ")";
        localDbDataSource.execute(sql);
    }

    /**
     * @see com.swift.dts.dao.ErrorSqlTableDao#delete(java.lang.Long)
     */
    @Override
    public void delete(Long sqlId) {
        String sql = "DELETE FROM " + ErrorSqlTable.TABLE_NAME + " WHERE sql_id=" + sqlId;
        localDbDataSource.execute(sql);
    }

    /**
     * @see com.swift.dts.dao.ErrorSqlTableDao#list(java.lang.String)
     */
    @Override
    public List<ErrorSqlTable> list(ErrorSqlTableKey key) {
        String sql = "SELECT * FROM " + ErrorSqlTable.TABLE_NAME + where(key) + " ORDER BY sql_id ";
        List<Map<String, Object>> list = localDbDataSource.queryForList(sql);
        if (TypeUtil.isNull(list)) return null;
        return JsonUtil.toListObject(JsonUtil.toJson(list), ErrorSqlTable.class);
    }

    /**
     * @see com.swift.dts.dao.ErrorSqlTableDao#list(java.lang.String, int, int)
     */
    @Override
    public List<ErrorSqlTable> list(ErrorSqlTableKey key, int start, int limit) {
        String sql = "SELECT * FROM " + ErrorSqlTable.TABLE_NAME + where(key) + " ORDER BY sql_id " + " OFFSET "+start+" ROWS " 
            + " FETCH NEXT "+limit+" ROWS ONLY ";
        List<Map<String, Object>> list = localDbDataSource.queryForList(sql);
        if (TypeUtil.isNull(list)) return null;
        return JsonUtil.toListObject(JsonUtil.toJson(list), ErrorSqlTable.class);
    }

    private String where(ErrorSqlTableKey key) {
        if (key == null) return " ";
        StringBuffer sb = new StringBuffer();
        if (TypeUtil.isNotNull( key.getDestination())) {
            if (sb.length() > 0) sb.append(" AND ");
            sb.append(" destination='" +  key.getDestination() + "' ");
        }
        if (TypeUtil.isNotNull(key.getDataSource())) {
            if (sb.length() > 0) sb.append(" AND ");
            sb.append(" data_source='" + key.getDataSource() + "' ");
        }
        if (TypeUtil.isNotNull(key.getDbName())) {
            if (sb.length() > 0) sb.append(" AND ");
            sb.append(" db_name='" + key.getDbName() + "' ");
        }
        if (TypeUtil.isNotNull(key.getTableName())) {
            if (sb.length() > 0) sb.append(" AND ");
            sb.append(" table_name='" + key.getTableName() + "' ");
        }
        if (TypeUtil.isNotNull(key.getPkKey())) {
            if (sb.length() > 0) sb.append(" AND ");
            sb.append(" pk_key='" + key.getPkKey() + "' ");
        }

        if (sb.length() <= 0) return " ";
        return " WHERE " + sb.toString();
    }

    /**
     * @see com.swift.dts.dao.ErrorSqlTableDao#count(java.lang.String)
     */
    @Override
    public int count(ErrorSqlTableKey key) {
        String sql = "SELECT COUNT(sql_id) AS count_num FROM " + ErrorSqlTable.TABLE_NAME + " " + where(key);
        Map<String, Object> rs = localDbDataSource.queryForMap(sql);
        if (TypeUtil.isNull(rs)) return 0;
        return TypeUtil.toInt(rs.get("count_num"), 0);
    }

    /**
     * @see com.swift.dts.dao.ErrorSqlTableDao#delete(com.swift.dts.dao.model.ErrorSqlTableKey)
     */
    @Override
    public void delete(ErrorSqlTableKey key) {
        String sql = "DELETE FROM " + ErrorSqlTable.TABLE_NAME + where(key);
        localDbDataSource.execute(sql);
    }

    /**
     * @see com.swift.dts.dao.ErrorSqlTableDao#writeSuccessSql(java.lang.String, com.swift.dts.model.DtsBinlogMessage,
     *      com.swift.dts.model.SqlObject)
     */
    @Override
    public void writeSuccessSql(String destination, DtsBinlogMessage message, SqlObject sqlObject) {
        ErrorSqlTableKey sql = new ErrorSqlTableKey();
        sql.setDataSource(message.getDestination());
        sql.setDestination(destination);
        sql.setDbName(message.getDatabase());
        sql.setTableName(message.getTable());
        sql.setPkKey(sqlObject.getPk());
        delete(sql);
    }

    /** 
     * @see com.swift.dts.dao.ErrorSqlTableDao#get(java.lang.Long)
     */
    @Override
    public ErrorSqlTable get(Long sqlId) {
        String sql = "SELECT * FROM " + ErrorSqlTable.TABLE_NAME + " WHERE sql_id=" + sqlId;
        Map<String, Object> map = localDbDataSource.queryForMap(sql);
        if (TypeUtil.isNull(map)) return null;
        return JsonUtil.toObj(JsonUtil.toJson(map), ErrorSqlTable.class);
    }

}
